package com.example.redistest.service;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.date.TimeInterval;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSONObject;
import com.example.redistest.entity.EleBaseAgencyEntity;
import com.example.redistest.mapper.AgencyRepository;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.data.redis.RedisProperties;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ConcurrentHashMap;

@Slf4j
@Service
public class AgencyService {
    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    @Autowired
    private AgencyRepository agencyRepository;
    
    public static final String KEY = "Agency:440000000:2020:";
    private final Logger logger = LoggerFactory.getLogger(this.getClass().getName());
    
    private static ConcurrentHashMap<String, List<EleBaseAgencyEntity>> cache = new ConcurrentHashMap<>();
    
    public List<EleBaseAgencyEntity> getAgency() {
        List<EleBaseAgencyEntity> result = new ArrayList<>();
    
        //优先命中内存缓存
//        List<EleBaseAgencyEntity> cacheResult = cache.get(KEY);
//        if (CollectionUtil.isNotEmpty(cacheResult)) {
//            logger.info("命中内存缓存");
//            return cacheResult;
//        }
        //从 redis 获取数据
        TimeInterval timer = DateUtil.timer();
        String json = stringRedisTemplate.opsForValue().get(KEY);
        logger.info("redis 获取数据耗时={}ms", timer.intervalMs());
        if (StrUtil.isNotBlank(json)) {
            timer.restart();
            result = JSONObject.parseArray(json, EleBaseAgencyEntity.class);
            logger.info("JSON 对象转换耗时={}ms,对象长度={}", timer.intervalMs(), result.size());
            cache.put(KEY, result);
            return result;
        }
        
        //从数据获取数据
        timer.restart();
        result = agencyRepository.findByTenantIdAndFiscalYear("440000000", "2021");
        logger.info("数据库查询耗时={}ms,对象长度={}", timer.intervalMs(), result.size());
        cache.put(KEY, result);
        if (CollectionUtil.isNotEmpty(result)) {
            timer.restart();
            stringRedisTemplate.opsForValue().set(KEY, JSONObject.toJSONString(result));
            logger.info("redis 存储数据耗时={}ms", timer.intervalMs());
        }
        return result;
    }
    
}
